package com.surelution.projects.crm

import java.text.SimpleDateFormat
import java.util.Map;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.grails.plugins.excelimport.ExcelImportUtils;

class CardPlanListController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	static Map CONFIG_CARD_PLAN_MAP = [
		sheet:"a",
		startRow: 0,
		columnMap:  [
			'A':'stationCode',
			'B':'station',
			'C':'planNumber',
		]
	]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
		def sdf = new SimpleDateFormat('yyyy-MM-dd')
		def dateFrom = params.dateFrom? sdf.parse(params.dateFrom):null
		def dateTo = params.dateTo? sdf.parse(params.dateTo):null
		def station = params['station.id']?OwnStation.get(params['station.id']):null
		def result = CardPlanList.createCriteria().list ([max:params.max, offset:params.offset]){
			if(station){
				eq("station",station)
			}
			if(dateFrom) {
				ge("planTime", dateFrom)
			}
			if(dateTo) {
				le("planTime", dateTo)
			}
			order("planTime","desc")
		}
        [cardPlanListInstanceList: result, cardPlanListInstanceTotal: result.totalCount]
    }

    def create = {
        def cardPlanListInstance = new CardPlanList()
        cardPlanListInstance.properties = params
        return [cardPlanListInstance: cardPlanListInstance]
    }
	
	def springSecurityService
	def ImportExcelService
	def cardPlan = {
		def file = params.cardPlan
		def fileName = file.originalFilename
		def time
		Date planTime
		Workbook workbook = WorkbookFactory.create(file.inputStream)
		List cardPlanList = ExcelImportUtils.columns(workbook, CONFIG_CARD_PLAN_MAP)
		cardPlanList.each{
			if (it.get("station") == "站名"){
				time = it.get("planNumber")
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM")
				planTime = sdf.parse(time)
			}
			else{
				String code = it.get("stationCode")
				code = code?code:0
				OwnStation station = OwnStation.findByCode(code)
				if(station!=null){
					if (!CardPlanList.findByStationAndPlanTime(station,planTime)&&station){
						CardPlanList cardPlan = new CardPlanList(stationCode:"${it.get("stationCode")}")
						cardPlan.planTime = planTime
						cardPlan.station = station
						float planNumber = Float.parseFloat("${it.get("planNumber")}")
						cardPlan.planNumber = planNumber
						flash.message = "${message(code: 'default.updateFileSuccess.message', args: [message(code: 'cardPlanList.label', default: 'cardPlanList')])}"
						cardPlan.save()
						println cardPlan
					}
					else{
						cardPlan = CardPlanList.findByStationAndPlanTime(station,planTime)
						float planNumber = Float.parseFloat("${it.get("planNumber")}")
						cardPlan.planNumber = planNumber
						cardPlan.save()
						flash.message = "${message(code: 'default.updateFileSuccess.message', args: [message(code: 'cardPlanList.label', default: 'cardPlanList')])}"
					}
				}
			}
		}
		ImportExcel excel = ImportExcelService.storeFile(file.inputStream,fileName)
		excel.uploader = springSecurityService.principal.username
		excel.type = "加油卡开卡量计划"
		excel.save()
		redirect(action:"list")
	}

    def save = {
        def cardPlanListInstance = new CardPlanList(params)
        if (cardPlanListInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'cardPlanList.label', default: 'CardPlanList'), cardPlanListInstance.id])}"
            redirect(action: "show", id: cardPlanListInstance.id)
        }
        else {
            render(view: "create", model: [cardPlanListInstance: cardPlanListInstance])
        }
    }

    def show = {
        def cardPlanListInstance = CardPlanList.get(params.id)
        if (!cardPlanListInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'cardPlanList.label', default: 'CardPlanList'), params.id])}"
            redirect(action: "list")
        }
        else {
            [cardPlanListInstance: cardPlanListInstance]
        }
    }

    def edit = {
        def cardPlanListInstance = CardPlanList.get(params.id)
        if (!cardPlanListInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'cardPlanList.label', default: 'CardPlanList'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [cardPlanListInstance: cardPlanListInstance]
        }
    }

    def update = {
        def cardPlanListInstance = CardPlanList.get(params.id)
        if (cardPlanListInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (cardPlanListInstance.version > version) {
                    
                    cardPlanListInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'cardPlanList.label', default: 'CardPlanList')] as Object[], "Another user has updated this CardPlanList while you were editing")
                    render(view: "edit", model: [cardPlanListInstance: cardPlanListInstance])
                    return
                }
            }
            cardPlanListInstance.properties = params
            if (!cardPlanListInstance.hasErrors() && cardPlanListInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'cardPlanList.label', default: 'CardPlanList'), cardPlanListInstance.id])}"
                redirect(action: "show", id: cardPlanListInstance.id)
            }
            else {
                render(view: "edit", model: [cardPlanListInstance: cardPlanListInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'cardPlanList.label', default: 'CardPlanList'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def cardPlanListInstance = CardPlanList.get(params.id)
        if (cardPlanListInstance) {
            try {
                cardPlanListInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'cardPlanList.label', default: 'CardPlanList'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'cardPlanList.label', default: 'CardPlanList'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'cardPlanList.label', default: 'CardPlanList'), params.id])}"
            redirect(action: "list")
        }
    }
}
